package xiaoa.java.zk.mgr;

import java.text.SimpleDateFormat;

import java.util.Date;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;

import xiaoa.java.zk.ZookeeperMgr;

/**
 * 生成key
 * @author xiaoa
 * @date 2017年1月9日 下午5:44:39
 * @version V1.0
 *
 */
public class KeyMgr {
	
	// 标记
	private static      String tag          = null;  
	
	// key
	private static final String KEY         = "key";
	
	// key 存储路径
	private static  String path             = null;
	
	// key 池
	private static BlockingQueue<Long>     keyPool  =  null;
	
	/**
	 * 初始化
	 * @Title: init
	 * @param tag
	 * @author xiaoa
	 */
	public static void  init ( String tag){
		KeyMgr.tag  = tag;
		
		KeyMgr.path = "/" +tag + "/" + KEY;
		
	}
	
	/**
	 * 获取key  返回为key 结束位置  （每日一刷新）
	 * @Title: getKey
	 * @param increment
	 * @return
	 * @throws Throwable
	 * @author xiaoa
	 */
	public static Long getDateKey(int increment)throws Throwable{
		
		if(increment <= 0 ){
			throw new RuntimeException("参数有误");
		}
		
		if(tag == null ){
			throw new RuntimeException("tag 未初始化");
		}
		
		// 获取当前日期
		String date  = new SimpleDateFormat("yyyyMMdd").format(new Date());
		
		// value 值
		String value = date + "," + increment;
		
	    // 如果路径不存在
	     if(!ZookeeperMgr.exists(path)){
	    	 
	    	 // 创建该路径
	    	 ZookeeperMgr.insert(path, value);
	    	 
	    	 return new Long(increment);
	     }
	     
	     
	     // 如果节点存在  获取节点值
	     value  =   ZookeeperMgr.get(path);
	     
	     // 分割value值
	     String[]  ss = value.split(",");
	     
	     Long  key  = null ;
	     
	     // 如果最近修改日期是当前日期
	     if(ss[0].equals(date)){
	    	 value = date + "," + (key = increment + Long.valueOf(ss[1]));
	    	 
	     }else{
	    	 value = date + "," + (key = Long.valueOf(increment) );
	     }
	     
	     // 修改  zk 值
	     ZookeeperMgr.update(path, value);
	     return key;
	}
	
	/**
	 * 获取一个key
	 * @Title: getKey
	 * @return
	 * @throws Throwable
	 * @author xiaoa
	 */
	public static synchronized long getKey()throws Throwable{
		
		// 如果没有key了
		if(keyPool == null){
			keyPool = new ArrayBlockingQueue<Long>(11000);
		}
		
		if(keyPool.size() == 0 ){
			// 先获取  10000 个 key
			long endKey =  getDateKey(10000);
			
			long start  = endKey - 10000 + 1;
			for(long key = start ; key <= endKey ; key ++ ){
				
				// 添加到池子中
				keyPool.add(key);
			}
		}
		
		return keyPool.remove();
	}
	
	
	public static void main(String[] args) {
		ArrayBlockingQueue<Long>  pool  = new ArrayBlockingQueue<>(10);
		
		pool.add(111l);
		pool.add(121l);		
		pool.add(1222l);
		pool.add(111l);
		pool.add(121l);		
		pool.add(1222l);

		pool.add(111l);
		pool.add(121l);		
		pool.add(1222l);
		pool.add(1222l);




		

		
	}
	
	

}
